import { Auths, Role } from '@/utils/types.d';
import {
  ProForm,
  ProFormCheckbox,
  ProFormSelect,
  ProFormSwitch,
  FooterToolbar,
  ProCard,
} from '@ant-design/pro-components';
import { useEffect, useState } from 'react';
import { useModel } from 'umi';
import { AdConfig } from './types.d';
import { editAdConfig, getAdConfig } from './service';
import { queryCompanies } from '../SystemUser/service';
import { message } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';

const DEFAULT = {
  adPosIds: [],
  medium: [],
  isEnable: false,
};

const AdConfigPages = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const isAdmin = currUser?.role === Role.ADMIN;
  const [ownerId, setOwnerId] = useState<string>(isAdmin ? '' : currUser?.ownerId || '');
  const [form] = ProForm.useForm();
  const [chillDowning, setChillDowning] = useState<number>(0);
  const auths = currUser?.auth ? new Set(currUser.auth.systemConfig || []) : new Set();
  const ifConfig = auths.has(Auths.AD_CONFIG);
  const [currConfig, setCurrConfig] = useState<AdConfig>(DEFAULT);
  if (chillDowning > -1) {
    setTimeout(() => {
      setChillDowning(chillDowning - 1);
    }, 1000);
  }
  useEffect(() => {
    if (!ownerId) return;
    getAdConfig(ownerId).then((res) => {
      if (!res || !res.data) return;

      setCurrConfig(res.data);
      form.setFieldsValue(res.data);
    });
  }, [ownerId]);
  return (
    <PageHeaderWrapper
      header={{
        breadcrumb: {
          routes: [
            {
              path: '/',
              breadcrumbName: '首页',
            },
            {
              path: '/setting-config',
              breadcrumbName: '系统配置',
            },
            {
              path: '/ad',
              breadcrumbName: '广告配置',
            },
          ],
        },
        subTitle: '广告配置',
      }}
      extra={
        isAdmin && (
          <ProFormSelect
            name="ownerId"
            label="配置公司"
            debounceTime={300}
            showSearch
            fieldProps={{
              value: ownerId,
              onChange: (val) => {
                if (ownerId != '') {
                  form?.setFieldsValue(DEFAULT);
                }
                setOwnerId(val);
              },
              style: {
                width: 280,
                margin: 0,
              },
            }}
            placeholder="请选择要进行配置公司"
            request={(val) => queryCompanies(val.keyWords, false)}
          />
        )
      }
    >
      <ProCard direction="column">
        <ProForm<AdConfig>
          form={form}
          submitter={{
            searchConfig: {
              submitText: ifConfig ? '保存配置' : '无权限操作',
            },
            submitButtonProps: {
              disabled: !ifConfig || chillDowning > 0,
            },
            render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
          }}
          initialValues={currConfig}
          onFinish={async (values) => {
            if (!ownerId) {
              message.warn({ content: '请选择配置公司', key: 'checkOwnerRes' });
              return;
            }
            setCurrConfig({
              ...values,
            });
            setChillDowning(10);
            const res = await editAdConfig({
              ownerId,
              adPosIds: values.adPosIds,
              medium: values.medium,
              isEnable: values.isEnable,
            });
            if (!res.success) {
              message.error({ content: res.message, key: 'editAdConfig' });
              return false;
            }
            message.success({ content: '保存成功', key: 'editAdConfig' });
            return true;
          }}
        >
          <ProFormCheckbox.Group
            name="adPosIds"
            layout="horizontal"
            label={<h3>广告位</h3>}
            options={[
              {
                label: '输入车牌页面',
                value: '3',
              },
              {
                label: '收银台页面',
                value: '4',
              },
              {
                label: '支付后页面',
                value: '5',
              },
            ]}
          />
          <ProFormCheckbox.Group
            name="medium"
            layout="horizontal"
            label={<h3>投放媒介</h3>}
            options={[
              {
                label: '公众号',
                value: '1',
              },
              {
                label: '小程序',
                value: '2',
              },
              {
                label: 'APP',
                value: '3',
              },
              {
                label: '支付宝生活号',
                value: '4',
              },
            ]}
          />
          <ProFormSwitch
            label={<h3>是否启用</h3>}
            name="isEnable"
            checkedChildren="启用"
            unCheckedChildren="关闭"
          />
        </ProForm>
      </ProCard>
    </PageHeaderWrapper>
  );
};

export default AdConfigPages;
